package com.guojiang.guopicturebackend.manager;

import cn.hutool.core.io.FileUtil;
import com.guojiang.guopicturebackend.config.CosClientConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.PicOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 对象存储通用类（与业务逻辑无关）
 */
@Component
public class CosManager {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private COSClient cosClient;

    /**
     * 将本地文件上传到 COS
     *
     * @param key  唯一键
     * @param file 文件
     * @return
     * @throws CosClientException
     * @throws CosServiceException
     */
    public PutObjectResult putObject(String key, File file) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key, file);
        // 调用客户端上传
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 删除对象
     *
     * @param url
     */
    public void deleteObject(String url) {
        // 调用客户端删除
        String key = extractKey(url);
        cosClient.deleteObject(cosClientConfig.getBucket(), key);
    }

    /**
     * 获取无域名的，用于删除图片对象的 Key
     * @param url
     * @return
     */
    public String extractKey(String url) {
        Pattern pattern = Pattern.compile("myqcloud.com(.*)");
        Matcher matcher = pattern.matcher(url);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return "";
    }

    /**
     * 下载对象
     *
     * @param key 唯一键
     * @return
     */
    public COSObject getObject(String key) {
        GetObjectRequest getObjectRequest = new GetObjectRequest(cosClientConfig.getBucket(), key);
        return cosClient.getObject(getObjectRequest);
    }

    /**
     * 上传图片对象（附带解析图片信息）
     *
     * @param key  唯一键
     * @param file 文件
     */
    public PutObjectResult putPictureObject(String key, File file) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key, file);
        // 对图片进行解析处理
        PicOperations picOperations = new PicOperations();
        // 是否返回原图信息，1 表示返回原图信息
        picOperations.setIsPicInfo(1);
        // 规则列表
        List<PicOperations.Rule> rules = new ArrayList<>();
        // 1. 构建压缩图片规则并加入规则列表
        PicOperations.Rule compressRule = new PicOperations.Rule();
        // 拼接压缩图片路径（转成 webp 格式）
        String webpKey = FileUtil.mainName(key) + ".webp";
        compressRule.setFileId(webpKey);
        compressRule.setBucket(cosClientConfig.getBucket());
        compressRule.setRule("imageMogr2/format/webp");
        rules.add(compressRule);
        // 2. 构造缩略图规则并加入规则列表（仅对原图大于 180KB 的增加缩略图，如果原图太小，压缩或缩略反而会使图片变大）
        if (file.length() > 180 * 1024) {
            PicOperations.Rule thumbnailRule = new PicOperations.Rule();
            // 拼接缩略图路径
            String thumbnailKey = FileUtil.mainName(key) + "_thumbnail." + FileUtil.getSuffix(key);
            thumbnailRule.setFileId(thumbnailKey);
            thumbnailRule.setBucket(cosClientConfig.getBucket());
            // 缩放规则：/thumbnail/<Width>x<Height>>（如果大于原图宽或高，则不会处理）
            thumbnailRule.setRule(String.format("imageMogr2/thumbnail/%sx%s>", 768, 768));
            rules.add(thumbnailRule);
        }
        // 构造处理参数
        // 设置图片处理规则列表
        picOperations.setRules(rules);
        putObjectRequest.setPicOperations(picOperations);
        // 调用客户端上传
        return cosClient.putObject(putObjectRequest);
    }
}
